package edu.hcnu.service.impl;

import edu.hcnu.domain.*;

import edu.hcnu.mapper.CustomerMapper;
import edu.hcnu.service.IUserService;
import edu.hcnu.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * @description:
 * @author: Administrator
 * @time: 2022/12/21 22:27
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private CustomerMapper sysUserMapper;




    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, Object> login(UserDTO userDTO) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        log.info(" 认证信息 {}", authenticate);

        if (Objects.isNull(authenticate)) {
            System.out.println("登录失败");
            throw new RuntimeException("登录失败");
        }
        if (authenticate.getPrincipal() instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String userid = String.valueOf(loginUser.getUser().getId());
            String jwt = JwtUtil.createJWT(userid);
            Map<String, Object> map = new HashMap<>();
            map.put("token", jwt);
            map.put("name", loginUser.getUser().getUsername());
            map.put("perm", loginUser.getPermissions());
            map.put("id", loginUser.getUser().getId());
            // token 30 分钟过期
            return map;
        }
        return null;
    }

    @Override
    public boolean logout() {

        Authentication authenticate = SecurityContextHolder.getContext().getAuthentication();

        if (authenticate.getPrincipal() instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            String userid = String.valueOf(loginUser.getUser().getId());
            return true;
        }

        return false;
    }

    @Override
    public boolean register(UserAddDTO userAddDTO) {
        return false;
    }

    @Override
    public boolean forget(UserForgetDTO userForgetDTO) {
        return false;
    }


}
